<?php

namespace App\Http\Controllers;

use App\Datas\User;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Validator;
use UAParser\Parser;
use Laravel\Lumen\Routing\Controller as BaseController;

class Controller extends BaseController
{

    const PAGE_SIZE = 10;

    protected function formatValidationErrors(Validator $validator)
    {
        // 返回参数错误
        return ['code' => Code::PARAM_ERROR, 'msg' => $validator->errors()->first()];
    }


    public function initRedisSession()
    {
        ini_set("session.save_handler", "redis");
        ini_set("session.save_path", sprintf("tcp://%s:%s?database=%s&auth=%s", env('REDIS_HOST'), env('REDIS_PORT'), env('REDIS_SESSION_DB'), env('REDIS_PASSWORD')));
        session_start();
    }

    // 设置token
    protected function setCookiesToken($token, $expire = 365*24*3600){
        setcookie('USER_TOKEN', $token, time() + $expire, '/');
        header('USER_TOKEN: '. $token);
        return true;
    }

    // 生成token
    protected function getRoundToken()
    {
        $token = md5(uniqid(md5(microtime(true)), true));
        return $token;
    }

    // 设置当前用户
    protected function setTokenUser($userId) {
        $token = $this->getRoundToken();
        $this->setCookiesToken($token);
        $dataUser = new User();
        $dataUser->setTokenUserId($token, $userId);
        return $token;
    }

    // 获取当前用户
    protected function getTokenUser() {
        $token = $_SERVER['HTTP_USER_TOKEN'] ?? $_COOKIE['USER_TOKEN'] ?? null;
        if ($token == 'test_token_1') {
            return 1;
        }
        if (!$token) {
            return null;
        }
        $dataUser = new User();
        $userId = $dataUser->getTokenUserId($token);
        return $userId;
    }

    // 清楚token
    protected function delTokenUser() {
        $this->setCookiesToken('');
    }

    // 返回值
    protected function buildReturn($code, $data=[], $msg = null) {

        return [
            'code' => $code,
            'data' => $data,
            'msg' => $msg ?? Code::$msg[$code]
        ];
    }


    // 获取设备ID
    public function getDeviceId() {
        return $_SERVER['HTTP_GUID'] ?? null;
    }

    // 获取版本号
    public function getVersion() {
        return $_SERVER['HTTP_AIVERSION'] ?? '1.0.2';
    }

    // 获取渠道号
    public function getChannel() {
        return $_SERVER['HTTP_AICHANNEL'] ?? '0';
    }

    // 获取当前语言
    public function getLanage() {
        //Log::info('getLanage', $_SERVER);
        return $_SERVER['HTTP_AI_LAN'] ?? 'en';
    }

    // 获取设备信息
    public function getModel() {
        $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
        $parser = Parser::create();
        $result = $parser->parse($ua);
        return $result->device->family ?? '';

    }

    // 获取包名
    public function getPkg() {
        return $_SERVER['HTTP_AIPKG'] ?? '';
    }

    // 获取安卓还是ios 1:ios 2:安卓
    public function getPlatform() {
        return $_SERVER['HTTP_PLATFORM'] ?? 1;
    }

    function aliasRandom($data)
    {
        $num = array_sum($data);
        $randomNum = mt_rand(1, $num);
        foreach ($data as $k => $v) {
            $randomNum = $randomNum - $v;
            if ($randomNum <= 0) {
                return $k;
            }
        }
        return null;
    }


    // 解析url参数
    function convertUrlQuery($query)
    {
        $queryParts = explode('&', $query);
        $params = array();
        foreach ($queryParts as $param) {
            $item = explode('=', $param);
            $params[$item[0]] = $item[1];
        }
        return $params;
    }

    public function getRealIp()
    {
        $ip = false;
        if(!empty($_SERVER["HTTP_CLIENT_IP"])) {
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }

        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
            if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
            for ($i = 0; $i < count($ips); $i++) {
                if (!eregi ("^(10│172.16│192.168).", $ips[$i])) {
                    $ip = $ips[$i];
                    break;
                }
            }
        }
        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
    }

    //付费前置
    public function checkNoLoginPay() {
        $version = $this->getVersion();
        $platform = $this->getPlatform();

        //苹果
        if ($platform == '1') {
            if (version_compare($version,'1.5.0') > 0) {
                return true;
            }
        } else {// 安卓
            if (version_compare($version,'1.6.0') > 0) {
                return true;
            }
        }

        return false;
    }
}
